<?php

class Admin extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model("check_model", "check");
        $this->load->model("admin_menu_model");
        $this->load->library('pagination');

        $this->_adminInfo = $this->check->checkAdminLogin();

        $this->projectUrl = [
            "add" => ADMIN_URL . "&c=admin&m=add",
            "list" => ADMIN_URL . "&c=admin&m=lists",
            "edit" => ADMIN_URL . "&c=admin&m=edit",
            "ajaxAdd" => ADMIN_URL . "&c=admin&m=ajaxAdd",
            "ajaxUpdate" => ADMIN_URL . "&c=admin&m=ajaxUpdate",
            "ajaxDel" => ADMIN_URL . "&c=admin&m=ajaxDel",
            "ajaxEditPassword" => ADMIN_URL . "&c=admin&m=ajaxEditPassword",
        ];
        $this->adminRoleUrl = [
            "add" => ADMIN_URL . "&c=admin&m=addAdminRole",
            "list" => ADMIN_URL . "&c=admin&m=adminRoleLists",
            "edit" => ADMIN_URL . "&c=admin&m=editAdminRole",
            "ajaxAdd" => ADMIN_URL . "&c=admin&m=ajaxAddAdminRole",
            "ajaxUpdate" => ADMIN_URL . "&c=admin&m=ajaxUpdateAdminRole",
            "ajaxDel" => ADMIN_URL . "&c=admin&m=ajaxDelAdminRole",
        ];
    }

    /*
     * 角色列表
     */

    function adminRoleLists() {

        #权限
        $this->check->checkPower(array("power" => "admin_role_view"));

        $data["navName"] = "角色列表";

        $page = $this->input->getInt("page", TRUE);
        if ($page <= 0) {
            $page = 1;
        }
        $pageCount = 20;
        $data["page"] = $page;
        $data["pageCount"] = $pageCount;

        $where = "where status_id>=0";
        $pageStrArr = array();

        //关键词
        $keyword = $this->input->getPostStr("keyword", TRUE);
        if ($keyword != "") {
            $pageStrArr["keyword"] = $keyword;
            $where .= " AND name LIKE '%" . $keyword . "%'";
        }
        $data["keyword"] = $keyword;

        $listNum = $this->admin->getAdminRoleCount($where);
        $dataList = $this->admin->getAdminRole($where, $page, $pageCount);

        $data["dataList"] = $dataList;

        #进行分页
        $pageStr = "";
        if (!empty($pageStrArr)) {
            foreach ($pageStrArr as $k => $v) {
                $pageStr .= "&" . $k . "=" . $v;
            }
        }
        $data['base_url'] = $this->adminRoleUrl["list"] . $pageStr;

        $data["listNum"] = $listNum;

        $this->layout->view('admin/admin/role/list', $data);
    }

    /*
     * 添加角色
     */

    function addAdminRole() {

        #权限
        $this->check->checkPower(array("power" => "admin_role_add"));

        $data["navName"] = "添加角色";

        $adminMenu = $this->admin_menu_model->getData("where status_id=1", 1, 0, "order by sort asc,id asc");
        $menu_data_tmp = [];
        foreach ($adminMenu as $k => $v) {
            $menu_data_tmp[$v["parent_id"]][$v["id"]] = [
                "title" => $v["title"],
                "id" => $v["id"],
                "checked" => false,
                "field" => "menu_id_arr[]",
                "spread" => true,
            ];
        }
        $menu_data = [];
        $i = 0;
        foreach ($menu_data_tmp[0] as $k => $v) {
            $menu_data[$i] = $v;
            if (isset($menu_data_tmp[$k])) {
                $j = 0;
                foreach ($menu_data_tmp[$k] as $k2 => $v2) {
                    $menu_data[$i]["children"][$j] = $v2;
                    if (isset($menu_data_tmp[$k2])) {
                        $p = 0;
                        foreach ($menu_data_tmp[$k2] as $k3 => $v3) {
                            $menu_data[$i]["children"][$j]["children"][$p] = $v3;
                            $p++;
                        }
                    }
                    $j++;
                }
            }
            $i++;
        }
        $data["menu_data"] = jsonEncode($menu_data);

        $adminPower = $this->admin->getAdminPower("where status_id=1", 1, 0, "order by order_id asc,id asc");
        $power_data_tmp = [];
        foreach ($adminPower as $k => $v) {
            $power_data_tmp[$v["parent_id"]][$v["id"]] = [
                "title" => $v["name"],
                "id" => $v["action_name"],
                "checked" => false,
                "field" => "power_id_arr[]",
                "spread" => true,
                "action_name" => $v["action_name"],
            ];
        }
        $power_data = [];
        $i = 0;
        foreach ($power_data_tmp[0] as $k => $v) {
            $power_data[$i] = $v;
            if (isset($power_data_tmp[$k])) {
                $j = 0;
                foreach ($power_data_tmp[$k] as $k2 => $v2) {
                    $power_data[$i]["children"][$j] = $v2;
                    if (isset($power_data_tmp[$k2])) {
                        $p = 0;
                        foreach ($power_data_tmp[$k2] as $k3 => $v3) {
                            $power_data[$i]["children"][$j]["children"][$p] = $v3;
                            $p++;
                        }
                    }
                    $j++;
                }
            }
            $i++;
        }
        $data["power_data"] = jsonEncode($power_data);

        $data["ajaxAddUrl"] = $this->adminRoleUrl["ajaxAdd"];

        $this->layout->view('admin/admin/role/add', $data);
    }

    /*
     * 编辑角色
     */

    function editAdminRole() {

        #权限
        $this->check->checkPower(array("power" => "admin_role_edit"));

        $data["navName"] = "编辑角色";

        #编辑角色
        $editId = $this->input->getInt("id", TRUE);
        if ($editId > 0) {
            $data["editId"] = $editId;
            $where = " WHERE id=" . $editId;
            $editData = $this->admin->getAdminRoleById($editId);
            if (!empty($editData)) {
                $data["editData"] = $editData;
            }
        }

        $adminMenu = $this->admin_menu_model->getData("where status_id=1", 1, 0, "order by sort asc,id asc");
        $menu_data_tmp = [];
        foreach ($adminMenu as $k => $v) {
            $menu_data_tmp[$v["parent_id"]][$v["id"]] = [
                "title" => $v["title"],
                "id" => $v["id"],
                "field" => "menu_id_arr[]",
                "spread" => true,
            ];
        }
        $menu_data = [];
        $i = 0;
        foreach ($menu_data_tmp[0] as $k => $v) {
            $menu_data[$i] = $v;
            $menu_data[$i]["checked"] = strrpos($editData["menu"], "|" . $v["id"] . "|") !== false ? true : false;
            if (isset($menu_data_tmp[$k])) {
                $j = 0;
                foreach ($menu_data_tmp[$k] as $k2 => $v2) {
                    $menu_data[$i]["children"][$j] = $v2;
                    $menu_data[$i]["children"][$j]["checked"] = strrpos($editData["menu"], "|" . $v2["id"] . "|") !== false ? true : false;
                    if ($menu_data[$i]["children"][$j]["checked"] == true) {
                        $menu_data[$i]["checked"] = false;
                    }
                    if (isset($menu_data_tmp[$k2])) {
                        $p = 0;
                        foreach ($menu_data_tmp[$k2] as $k3 => $v3) {
                            $menu_data[$i]["children"][$j]["children"][$p] = $v3;
                            $menu_data[$i]["children"][$j]["children"][$p]["checked"] = strrpos($editData["menu"], "|" . $v3["id"] . "|") !== false ? true : false;
                            if ($menu_data[$i]["children"][$j]["children"][$p]["checked"] == true) {
                                $menu_data[$i]["children"][$j]["checked"] = false;
                            }
                            $p++;
                        }
                    }
                    $j++;
                }
            }
            $i++;
        }
        $data["menu_data"] = jsonEncode($menu_data);

        $adminPower = $this->admin->getAdminPower("where status_id=1", 1, 0, "order by order_id asc,id asc");
        $power_data_tmp = [];
        foreach ($adminPower as $k => $v) {
            $power_data_tmp[$v["parent_id"]][$v["id"]] = [
                "title" => $v["name"],
                "id" => $v["action_name"],
                "field" => "power_id_arr[]",
                "spread" => true,
                "action_name" => $v["action_name"],
            ];
        }
        $power_data = [];
        $i = 0;
        foreach ($power_data_tmp[0] as $k => $v) {
            $power_data[$i] = $v;
            $power_data[$i]["checked"] = strrpos($editData["power"], "|" . $v["action_name"] . "|") !== false ? true : false;
            if (isset($power_data_tmp[$k])) {
                $j = 0;
                foreach ($power_data_tmp[$k] as $k2 => $v2) {
                    $power_data[$i]["children"][$j] = $v2;
                    $power_data[$i]["children"][$j]["checked"] = strrpos($editData["power"], "|" . $v2["action_name"] . "|") !== false ? true : false;
                    if ($power_data[$i]["children"][$j]["checked"] == true) {
                        $power_data[$i]["checked"] = false;
                    }
                    if (isset($power_data_tmp[$k2])) {
                        $p = 0;
                        foreach ($power_data_tmp[$k2] as $k3 => $v3) {
                            $power_data[$i]["children"][$j]["children"][$p] = $v3;
                            $power_data[$i]["children"][$j]["children"][$p]["checked"] = strrpos($editData["power"], "|" . $v3["action_name"] . "|") !== false ? true : false;
                            if ($power_data[$i]["children"][$j]["children"][$p]["checked"] == true) {
                                $power_data[$i]["children"][$j]["checked"] = false;
                            }
                            $p++;
                        }
                    }
                    $j++;
                }
            }
            $i++;
        }
        $data["power_data"] = jsonEncode($power_data);

        $data["ajaxAddUrl"] = $this->adminRoleUrl["ajaxUpdate"];

        $this->layout->view('admin/admin/role/add', $data);
    }

    /*
     * ajax添加角色
     */

    function ajaxAddAdminRole() {

        #权限
        $this->check->checkPower(array("power" => "admin_role_add", "ajax" => 1));

        $flag = false;
        $msg = "操作失败";
        $name = $this->input->postStr("name", TRUE);
        $power_id_arr = $this->input->postStr("power_id_arr", TRUE, false);
        $menu_id_arr = $this->input->postStr("menu_id_arr", TRUE, false);
        $remark = $this->input->postStr("remark", TRUE);

        $power = "";
        if (!empty($power_id_arr)) {
            $power = "|" . implode("|", $power_id_arr) . "|";
        }
        $menu = "";
        if (!empty($menu_id_arr)) {
            $menu = "|" . implode("|", $menu_id_arr) . "|";
        }

        if ($name == "") {
            $msg = "参数错误";
        } else {
            $data = array(
                "name" => $name,
                "power" => $power,
                "menu" => $menu,
                "remark" => $remark,
                "add_time" => time(),
            );
            $result = $this->admin->addAdminRole($data);
            if ($result) {
                $flag = true;
                $msg = "操作成功";
            }
        }

        $outArr = array("flag" => $flag, "msg" => $msg);
        echo json_encode($outArr);
    }

    /*
     * ajax修改角色
     */

    function ajaxUpdateAdminRole() {

        #权限
        $this->check->checkPower(array("power" => "admin_role_edit", "ajax" => 1));

        $flag = false;
        $msg = "操作失败";
        $name = $this->input->postStr("name", TRUE);
        $menu_id_arr = $this->input->postStr("menu_id_arr", TRUE, false);
        $power_id_arr = $this->input->postStr("power_id_arr", TRUE, false);
        $remark = $this->input->postStr("remark", TRUE);

        $editId = $this->input->postInt("id", TRUE);

        $power = "";
        if (!empty($power_id_arr)) {
            $power = "|" . implode("|", $power_id_arr) . "|";
        }
        $menu = "";
        if (!empty($menu_id_arr)) {
            $menu = "|" . implode("|", $menu_id_arr) . "|";
        }
        if ($name == "" || $editId <= 0) {
            $msg = "参数错误";
        } else {
            $paramArr = array(
                "fieldArr" => array(
                    "name" => $name,
                    "power" => $power,
                    "menu" => $menu,
                    "remark" => $remark,
                ),
                "whereArr" => array("id" => $editId),
            );
            $result = $this->admin->updateAdminRole($paramArr);
            if ($result) {
                $flag = true;
                $msg = "操作成功";
            }
        }

        $outArr = array("flag" => $flag, "msg" => $msg);
        echo json_encode($outArr);
    }

    /*
     * 删除记录
     */

    public function ajaxDelAdminRole() {

        #权限
        $this->check->checkPower(array("power" => "admin_role_del", "ajax" => 1));

        $flag = false;
        $msg = "操作失败";
        $delId = $this->input->postStr("id", TRUE);
        if ($delId > 0) {
            $paramArr = array(
                "whereArr" => array(
                    "id" => $delId
                ),
            );
            $result = $this->admin->delAdminRole($paramArr);
            if ($result) {
                $flag = true;
                $msg = "操作成功";
            }
        } else {
            $msg = "参数有误";
        }
        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * 添加用户
     */

    function add() {

        #权限
        $this->check->checkPower(array("power" => "admin_add"));

        $data["navName"] = "添加用户";

        $data["adminRole"] = $this->admin->getAdminRole("WHERE status_id>=0", "", "", "", "id,name");
        $data["status"] = $this->common->getStatus();

        $data["ajaxAddUrl"] = $this->projectUrl["ajaxAdd"];

        $this->layout->view('admin/admin/user/add', $data);
    }

    /*
     * 编辑用户
     */

    function edit() {

        #权限
        $this->check->checkPower(array("power" => "admin_edit"));

        $data["navName"] = "编辑用户";

        $data["adminRole"] = $this->admin->getAdminRole("WHERE status_id>=0", "", "", "", "id,name");
        $data["status"] = $this->common->getStatus();

        #编辑角色
        $editId = $this->input->getInt("id", TRUE);
        if ($editId > 0) {

            $data["editId"] = $editId;
            $where = " WHERE id=" . $editId;
            $editData = $this->admin->getAdminInfo($where, 1, 1);
            if (!empty($editData)) {
                $data["editData"] = $editData[0];
            }
        }
        $data["ajaxAddUrl"] = $this->projectUrl["ajaxUpdate"];

        $this->layout->view('admin/admin/user/add', $data);
    }

    /*
     * ajax添加用户
     */

    function ajaxAdd() {

        #权限
        $this->check->checkPower(array("power" => "admin_add", "ajax" => 1));

        $flag = false;
        $msg = "操作失败";
        $username = $this->input->postStr("username", TRUE);
        $password = $this->input->postStr("password", TRUE);
        $truename = $this->input->postStr("truename", TRUE);
        $role_id = $this->input->postInt("role_id", TRUE);
        $remark = $this->input->postStr("remark", TRUE);
        $status_id = $this->input->postInt("status_id", TRUE);

        if ($password != "") {
            $password = $this->common->encryptPassword($password);
        }

        if ($username == "" || $password == "" || $truename == "" || $role_id <= 0) {
            $msg = "参数错误";
        } else {

            $data = array(
                "username" => $username,
                "password" => $password,
                "truename" => $truename,
                "role_id" => $role_id,
                "remark" => $remark,
                "status_id" => $status_id,
                "add_time" => time(),
            );
            $result = $this->admin->addAdminInfo($data);
            if ($result) {
                $flag = true;
                $msg = "操作成功";
            }
        }

        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * ajax编辑用户
     */

    function ajaxUpdate() {

        #权限
        $this->check->checkPower(array("power" => "admin_edit", "ajax" => 1));

        $flag = false;
        $msg = "操作失败";
        $username = $this->input->postStr("username", TRUE);
        $password = $this->input->postStr("password", TRUE);
        $truename = $this->input->postStr("truename", TRUE);
        $role_id = $this->input->postInt("role_id", TRUE);
        $remark = $this->input->postStr("remark", TRUE);
        $status_id = $this->input->postInt("status_id", TRUE);
        $editId = $this->input->postInt("id", TRUE);

        if ($username == "" || $truename == "" || $role_id <= 0 || $editId <= 0) {
            $msg = "参数错误";
        } else {

            $paramArr = array(
                "fieldArr" => array(
                    "username" => $username,
                    "truename" => $truename,
                    "role_id" => $role_id,
                    "remark" => $remark,
                    "status_id" => $status_id,
                ),
                "whereArr" => array(
                    "id" => $editId,
                ),
            );
            if ($password != "") {
                $password = $this->common->encryptPassword($password);
                $paramArr["fieldArr"]["password"] = $password;
            }
            $result = $this->admin->updateAdminInfo($paramArr);
            if ($result) {
                $flag = true;
                $msg = "操作成功";
            }
        }
        $outArr = array("flag" => $flag, "msg" => $msg);
        echo json_encode($outArr);
    }

    /*
     * 用户列表
     */

    function lists() {

        #权限
        $this->check->checkPower(array("power" => "admin_view"));

        $data["navName"] = "用户列表";

        $page = $this->input->getInt("page", TRUE);
        if ($page <= 0) {
            $page = 1;
        }
        $pageCount = 20;
        $data["pageCount"] = $pageCount;
        $data["page"] = $page;

        $where = "where 1";
        $pageStrArr = array();

        //关键词
        $keyword = $this->input->getPostStr("keyword", TRUE);
        if ($keyword != "") {
            $pageStrArr["keyword"] = $keyword;
            $where .= " AND ( username LIKE '%" . $keyword . "%' OR truename LIKE '%" . $keyword . "%' ) ";
        }
        $data["keyword"] = $keyword;

        $listNum = $this->admin->getAdminInfoCount($where);
        $dataList = $this->admin->getAdminInfo($where, $page, $pageCount);

        $status = $this->common->getStatus();
        $adminRole = $this->admin->getAdminRoleByKey();
        foreach ($dataList as $k => $v) {
            $dataList[$k]["statusTag"] = !empty($status[$v["status_id"]]["tag"]) ? $status[$v["status_id"]]["tag"] : "-";
            $dataList[$k]["roleName"] = !empty($adminRole[$v["role_id"]]["name"]) ? $adminRole[$v["role_id"]]["name"] : "-";
        }

        $data["dataList"] = $dataList;

        #进行分页
        $pageStr = "";
        if (!empty($pageStrArr)) {
            foreach ($pageStrArr as $k => $v) {
                $pageStr .= "&" . $k . "=" . $v;
            }
        }

        $data["listNum"] = $listNum;
        $data["base_url"] = $this->projectUrl["list"] . $pageStr;

        $this->layout->view('admin/admin/user/list', $data);
    }

    /*
     * 删除用户
     */

    public function ajaxDel() {

        #权限
        $this->check->checkPower(array("power" => "admin_del", "ajax" => 1));

        $flag = false;
        $msg = "操作失败";
        $delId = $this->input->postInt("id", TRUE);
        if ($delId > 0) {
            $paramArr = array(
                "whereArr" => array(
                    "id" => $delId
                ),
            );
            $result = $this->admin->delAdminInfo($paramArr);
            if ($result) {
                $flag = true;
                $msg = "操作成功";
            }
        } else {
            $msg = "参数有误";
        }
        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * 修改密码
     */

    function editPassword() {

        $data["navName"] = "修改密码";

        $this->layout->view('admin/admin/editPassword', $data);
    }

    /*
     * ajax修改用户密码
     */

    function ajaxEditPassword() {

        $flag = false;
        $msg = "操作失败";

        $password_old = $this->input->postStr("password_old", TRUE);
        $password = $this->input->postStr("password", TRUE);
        $password_re = $this->input->postStr("password_re", TRUE);

        if ($password_old == "" || $password == "" || $password_re == "") {
            $msg = "参数错误";
        } else {

            $password_old = $this->common->encryptPassword($password_old);

            $username = $this->_adminInfo["username"];
            $password_data = $this->_adminInfo["password"];

            if ($password_old != $password_data) {
                $msg = "旧密码错误";
            } else {
                $password = $this->common->encryptPassword($password);

                $paramArr = array(
                    "fieldArr" => array(
                        "password" => $password,
                    ),
                    "whereArr" => array(
                        "username" => $username,
                    ),
                );
                $result = $this->admin->updateAdminInfo($paramArr);
                if ($result) {
                    $flag = true;
                    $msg = "操作成功";

                    $res = $this->admin->checkAdminLogin($username, $password);
                    $sessionData = [
                        'session_admin_user_id' => $res['id'],
                        'session_admin_user_username' => $username,
                        'session_admin_user_is_login' => 1,
                    ];
                    $this->session->set_userdata($sessionData);
                }
            }
        }
        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

}
